package com.tansun.easycare.rule.common;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeedev.msdp.base.entity.SysUser;
import com.tansun.easycare.core.web.BaseController;
import com.tansun.easycare.modules.sys.utils.UserUtils;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.service.RuleBaseService;
import com.tansun.easycare.rule.common.web.model.ProjectInfo;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.LoggerManager;

/**
 * 控制层对象通用父类
 *
 * @author WY
 */
public class RuleBaseController extends BaseController {

	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
    @Autowired
    private RuleManageService ruleManageService;

    private RuleBaseService<?> ruleBaseService;
    @Autowired
    private DataModelService dataModelService;
    @Autowired
    private HttpServletRequest request;

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 时间格式化对象
     */
    public SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    /**
     * 模型类型映射对象，常规查询数据
     */
    public static Map<String, String> RuleModelMap = null;

    /**
     * 设置当前项目编码
     */
    public void setCurrProjectCode(String projectCode) {
        request.getSession().setAttribute("CURRPROJECTCODE", projectCode);
    }

    /**
     * 获取当前项代码
     *
     * @return 当前项代码
     */
    public String getCurrProjectCode() throws Exception {
        Object obj = request.getSession().getAttribute("CURRPROJECTCODE");
        
        String projectCode = request.getParameter("projectCode");
    	if(projectCode!=null&&!"".equals(projectCode)){
    		obj = projectCode;
    	}
        if (RuleModelMap == null) {
            RuleModelMap = new HashMap<String, String>();
            RuleModelMap.put("dataModel", "数据模型");
            RuleModelMap.put("segmentation", "分段细分");
            RuleModelMap.put("conditionalSub", "条件细分");
            RuleModelMap.put("decisionTree", "决策树");
            RuleModelMap.put("policyTree", "策略树");
            RuleModelMap.put("decisionTable", "决策表");
            RuleModelMap.put("evaluationIndex", "赋值索引");
            RuleModelMap.put("singleTblIndex", "决策表");
            RuleModelMap.put("scoreModel", "评分模型");
            RuleModelMap.put("generalRule", "普通规则");
            RuleModelMap.put("ruleGroup", "规则集");
            RuleModelMap.put("policyRuleGroup", "规则集");
            RuleModelMap.put("ruleFlow", "决策流");
        }
        if (obj == null)
            throw new Exception("项目编码丢失，请刷新页面");
        return obj.toString();
    }

    /**
     * 获取当前用户信息
     */
    public SysUser getCurrUser() {
        return UserUtils.getSysService().getCurrUser();
    }

    /**
     * 修改规则 项目状态
     *
     * @param treeId 决策树或策略树ID
     * @param status 要修改的状态（0：删除，2：发布）
     * @return 是否切换成功
     */
    @RequestMapping("statusChange")
    public  ResponseVO statusChange(@RequestBody ProjectInfo projectInfo) throws Exception {
    	ResponseVO ret = new ResponseVO();
        setRuleBizService();
        try {
            if ("2".equals(projectInfo.getStatus())) {
                ruleManageService.setRuleBaseService(this.ruleBaseService);
                ruleManageService.publicRule(projectInfo.getManageId());
            } else if ("0".equals(projectInfo.getStatus())) {
            	RuleManage ruleManage = ruleManageService.get(projectInfo.getManageId());
            	dataModelService.deleteBuiltinParam(ruleManage.getCode(), ruleManage.getName(), ruleManage.getModelType(), ruleManage.getProjectCode());
            	List<ReferenceModel> referenceList = ruleManageService.delete(projectInfo.getManageId(),projectInfo.getProjectCode());
            	if(referenceList.size()>0) {
            		ret.setData((Serializable) referenceList);
            		ret.setStatus(ResponseVO.ERROR);
            		ret.setDescription("该规则模型被其他组件引用，无法删除！");
            	}else if("21".equals(ruleManage.getModelType())) {
            		DataCache.ruleSetEffectChange(ruleManage.getProjectCode());
            	}
            }
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);
            ret.setDescription("回退失败："+e.getMessage());
        }
        return ret;
    }

    /**
     * 切换决策树模型版本
     *
     * @param scoreId 评分模型ID
     * @param version 要切换的版本
     * @return 是否切换成功
     */
    @RequestMapping("revertVersion")
    public  ResponseVO revertVersion(@RequestBody ProjectInfo projectInfo) throws Exception {
    	ResponseVO ret = new ResponseVO();
        try {
            setRuleBizService();
            ruleManageService.setRuleBaseService(this.ruleBaseService);
            ruleManageService.publicRule(projectInfo.getManageId(), projectInfo.getVersion());
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);
            if (e instanceof ApplicationContextException) {
                ret.setDescription(e.getMessage());
            } else {
                ret.setDescription("回退失败，请查看日志");
            }
        }
        return ret;
    }

    /**
     * 表类规则复制
     */
    @RequestMapping("copyRule")
    public ResponseVO copyRule(@RequestBody  ProjectInfo  projectInfo) {
    	ResponseVO ret = new ResponseVO();
        try {
            setRuleBizService();
            ruleManageService.setRuleBaseService(this.ruleBaseService);
            this.ruleManageService.copyRule(projectInfo.getManageId(),projectInfo.getRankRelationId());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(e.getMessage(), e);
            ret.setStatus(ResponseVO.ERROR);
            ret.setDescription(e.getMessage());
        }
        return ret;
    }




    public void setRuleBaseService( RuleBaseService<?> ruleBaseService) {
        this.ruleBaseService = ruleBaseService;
    }

    public void setRuleBizService() {

    }


}
